package com.dxjy.demo.module.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSONObject;
import com.dxjy.demo.entity.R;
import com.dxjy.demo.module.sys.entity.SysDep;
import com.dxjy.demo.module.sys.mapper.SysUserMapper;
import com.dxjy.demo.module.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhang
 * @Date: 2021/8/31 9:49
 * @Description:
 * @Version: 1.0
 */
@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;


	@Override
	public R getUserList() {
		List<JSONObject> userInfoList = sysUserMapper.getUserInfoList();
		return R.okList(userInfoList);
	}

	@Override
	public R getDepTerrList() {
		// 构建node列表
		List<TreeNode<String>> nodeList = CollUtil.newArrayList();

		List<SysDep> depList = sysUserMapper.getDepList();
		for (SysDep dep : depList) {
			Map<String,Object> map = new HashMap<>();
			map.put("createDate", DateUtil.formatDateTime(dep.getCreateDate()));
			map.put("status", dep.getStatus());
			nodeList.add(new TreeNode<>(String.valueOf(dep.getId()), String.valueOf(dep.getPid()),
					dep.getName(), dep.getSort())
					.setExtra(map));
		}

		//配置
		TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
		// 自定义属性名 都要默认值的
		treeNodeConfig.setWeightKey("sort");
		treeNodeConfig.setParentIdKey("pId");
		// 最大递归深度
		treeNodeConfig.setDeep(3);

		//转换器
		List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "0", treeNodeConfig,
				(treeNode, tree) -> {
					tree.setId(treeNode.getId());
					tree.setParentId(treeNode.getParentId());
					tree.setWeight(treeNode.getWeight());
					tree.setName(treeNode.getName());
					// 扩展属性 ...
					tree.putExtra("date", treeNode.getExtra().get("createDate"));
					tree.putExtra("status", treeNode.getExtra().get("status"));
				});

//		List<Tree<String>> treeList = TreeUtil.build(nodeList, "0");


		return R.okList(treeNodes);
	}
}
